package cn.com.homeyoda.aimate.aihealth.ui.health.viewModel;

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.wzq.mvvmsmart.event.StateLiveData;
import com.wzq.mvvmsmart.utils.KLog;
import com.wzq.mvvmsmart.utils.RxUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.com.homeyoda.aimate.aihealth.base.BaseViewModel;
import cn.com.homeyoda.aimate.aihealth.bean.ChronicDiseaseItemBean;
import cn.com.homeyoda.aimate.aihealth.bean.FaceInfoBean;
import cn.com.homeyoda.aimate.aihealth.bean.FamilyMembersBean;
import cn.com.homeyoda.aimate.aihealth.bean.InspectionScheduleTypeBean;
import cn.com.homeyoda.aimate.aihealth.data.Repository;
import cn.com.homeyoda.aimate.aihealth.manager.UserInfoManager;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 饮食计划
 */
public class ChronicDiseaseViewMode extends BaseViewModel<Repository> {

    public StateLiveData<FamilyMembersBean.DataBean.FamilyMembers> planUserStateLiveData;

    public StateLiveData<List<ChronicDiseaseItemBean.DataBean>> diseaseTitleList;

    public StateLiveData<List<ChronicDiseaseItemBean.DataBean>> chroincDiseaseSelectList;

    public StateLiveData<List<InspectionScheduleTypeBean.DataBean>> visualLiveData;

    public StateLiveData<FaceInfoBean> faceInfoBeanStateLiveData;


    public ChronicDiseaseItemBean.DataBean defTitle;


    public ArrayList<FamilyMembersBean.DataBean.FamilyMembers> familyMembers;

    public int titleSelectPosition = 0;

    public ChronicDiseaseViewMode(@NonNull Application application, Repository model) {
        super(application, model);
        planUserStateLiveData = new StateLiveData<>();
        diseaseTitleList = new StateLiveData<>();
        chroincDiseaseSelectList = new StateLiveData<>();
        visualLiveData = new StateLiveData<>();
        faceInfoBeanStateLiveData = new StateLiveData<>();
    }


    /**
     * 用户列表
     */
    public void initUserInfo() {
        if (TextUtils.isEmpty(model.getUserId())) {
            Log.d(TAG, "initUserInfo error : not login !");
            return;
        }

        model.getFamilyMembers(model.getFamilyId())
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new Observer<FamilyMembersBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        planUserStateLiveData.setLoading();
                    }

                    @Override
                    public void onNext(FamilyMembersBean response) {
                        if (response.getCode() == 200) {
                            familyMembers = response.getData().getFamilyMembers();
                            if (familyMembers.size() > 0){
                                for (FamilyMembersBean.DataBean.FamilyMembers userMember : familyMembers) {
                                    if (model.getUserId().equals(String.valueOf(userMember.getUserId()))) {
                                        planUserStateLiveData.setValueAndSuccess(userMember);
                                    }
                                }

                                if (planUserStateLiveData.getValue() == null && familyMembers.size() > 0) {
                                    planUserStateLiveData.setValueAndSuccess(familyMembers.get(0));
                                }
                            }else {
                                planUserStateLiveData.setError();
                            }


                        } else {
                            planUserStateLiveData.setError();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError" + e.getMessage());
                        planUserStateLiveData.setError();
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                        planUserStateLiveData.setIdle();
                    }
                });
    }

    /**
     * 初始化慢性病选择列表数据
     */
    public void initSelectData() {

        model.attentionChronicList()
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new Observer<ChronicDiseaseItemBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        chroincDiseaseSelectList.postLoading();
                    }

                    @Override
                    public void onNext(ChronicDiseaseItemBean chronicDiseaseItemBean) {
                        if (chronicDiseaseItemBean.getCode() == 200) {
                            List<ChronicDiseaseItemBean.DataBean> dataBeans = chronicDiseaseItemBean.getData();
                            for (ChronicDiseaseItemBean.DataBean dataBean : dataBeans) {
                                if (UserInfoManager.getInstance().chronicDiseaseMap.containsKey(dataBean.getDictCode())) {
                                    dataBean.setSelect(true);
                                } else {
                                    dataBean.setSelect(false);
                                }
                            }

                            chroincDiseaseSelectList.postValueAndSuccess(dataBeans);
                        } else {
                            chroincDiseaseSelectList.postError();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        chroincDiseaseSelectList.postError();
                    }

                    @Override
                    public void onComplete() {
                        chroincDiseaseSelectList.postIdle();
                    }
                });

    }

    /**
     * 新增慢性病
     *
     * @param dictCodes
     */
    public void attentionChronicAdd(String dictCodes) {
        model.attentionChronicAdd(planUserStateLiveData.getValue().getFaceId(), dictCodes)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new Observer<ChronicDiseaseItemBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ChronicDiseaseItemBean chronicDiseaseItemBean) {
                        if (chronicDiseaseItemBean.getCode() == 200) {
                            Log.d(TAG, "add success");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public void initChronicDisease() {
        List<ChronicDiseaseItemBean.DataBean> titles = new ArrayList<>();
        titles.addAll(UserInfoManager.getInstance().chronicDiseaseMap.values());
        diseaseTitleList.postValueAndSuccess(titles);
    }

    public void setTitleSelectPosition(int position) {

        if (diseaseTitleList.getValue() == null || diseaseTitleList.getValue().size() == 0) {
            Log.e(TAG, "setTitleSelectPosition error: diseaseTitleList is empty");
            return;
        }

        if (diseaseTitleList.getValue().size() > position) {
            titleSelectPosition = position;
        } else {
            titleSelectPosition = 0;
        }
        defTitle = diseaseTitleList.getValue().get(titleSelectPosition);

        model.inspectinsScheduleType(planUserStateLiveData.getValue().getFaceId(), defTitle.getType(), "", "", "8", "1", "asc")
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new Observer<InspectionScheduleTypeBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        visualLiveData.postLoading();
                    }

                    @Override
                    public void onNext(InspectionScheduleTypeBean inspectionScheduleTypeBean) {
                        if (inspectionScheduleTypeBean.getCode() == 200) {
                            List<InspectionScheduleTypeBean.DataBean> datas = inspectionScheduleTypeBean.getData();
                            // 倒序排序
                            Collections.reverse(datas);
                            visualLiveData.postValueAndSuccess(datas);
                        } else {
                            visualLiveData.postError();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        visualLiveData.postError();
                    }

                    @Override
                    public void onComplete() {
                        visualLiveData.postIdle();
                    }
                });

    }


    public void changeMember(FamilyMembersBean.DataBean.FamilyMembers member) {
        if (member != null && member.getId() != planUserStateLiveData.getValue().getId()) {
            planUserStateLiveData.setValue(member);
            planUserStateLiveData.postValue(member);
        }

    }


    public void queryFaceInfo() {
        model.queryFaceInfo(planUserStateLiveData.getValue().getFaceId(), model.getFamilyId())
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new Observer<FaceInfoBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        faceInfoBeanStateLiveData.postLoading();
                    }

                    @Override
                    public void onNext(FaceInfoBean faceInfoBean) {
                        if (faceInfoBean.getCode() == 200) {
                            List<FaceInfoBean.DataBean.AttentionChronicListBean> chronicListBeans = faceInfoBean.getData().getAttentionChronicList();
                            UserInfoManager.getInstance().chronicDiseaseMap.clear();
                            for (FaceInfoBean.DataBean.AttentionChronicListBean bean : chronicListBeans) {
                                ChronicDiseaseItemBean.DataBean dataBean = new ChronicDiseaseItemBean.DataBean();
                                dataBean.setName(bean.getName());
                                dataBean.setType(bean.getType());
                                dataBean.setDictCode(bean.getDictCode());
                                UserInfoManager.getInstance().chronicDiseaseMap.put(bean.getDictCode(), dataBean);
                            }

                            faceInfoBeanStateLiveData.postValueAndSuccess(faceInfoBean);
                        } else {
                            faceInfoBeanStateLiveData.postError();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        faceInfoBeanStateLiveData.postError();
                    }

                    @Override
                    public void onComplete() {
                        faceInfoBeanStateLiveData.postIdle();
                    }
                });

    }

}
